# -*- coding:utf-8 -*-
from huaweicloudsdkcore.auth.credentials import GlobalCredentials
from huaweicloudsdkcdn.v1.region.cdn_region import CdnRegion
from huaweicloudsdkcdn.v1 import *


def handler(event, context):
    log = context.getLogger()
    ak = context.getAccessKey()
    sk = context.getSecretKey()
    if ak == "" or sk == "":
        log.error("AK of SK is empty. Please set an agency.")
        return "FAILED"

    domain = context.getUserData("domain", "https://xxx.com/")
    record = event['Records'][0]
    (bucket, object_key) = get_obs_obj_info(record)
    log.info("src bucket:" + bucket)
    log.info("src object_key:" + object_key)

    credentials = GlobalCredentials(ak, sk)
    client = CdnClient.new_builder() \
        .with_credentials(credentials) \
        .with_region(CdnRegion.value_of("cn-north-1")) \
        .build()
    request = CreateRefreshTasksRequest()
    listUrlsRefreshTask = [
        domain+object_key
    ]
    refreshTaskbody = RefreshTaskRequestBody(
        type="file",
        urls=listUrlsRefreshTask
    )
    request.body = RefreshTaskRequest(
        refresh_task=refreshTaskbody
    )
    response = client.create_refresh_tasks(request)
    log.info("create refresh task result: %s", response)
    return "SUCCESS"


def get_obs_obj_info(record):
    if 's3' in record:
        s3 = record['s3']
        return s3['bucket']['name'], s3['object']['key']
    else:
        obs_info = record['obs']
        return obs_info['bucket']['name'], obs_info['object']['key']
